package com.nciae.chain.handler.security;

import com.nciae.po.SecurityQuestion;
import com.nciae.po.Teacher;
import com.nciae.po.TeacherSecurityQuestion;
import com.nciae.service.ITeacherSecurityQuestionService;
import com.nciae.service.ITeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Component
@Order(1)
public class TeacherSecurityQuestionHandler implements QHandler {

    @Autowired
    private ITeacherSecurityQuestionService teacherSecurityQuestionService;

    @Autowired
    private ITeacherService teacherService;

    @Override
    public void service(SecurityQuestion securityQuestion, int option) {

        // teacher,add
        if (!Objects.isNull(securityQuestion.getTeacher()) && !Objects.isNull(securityQuestion.getTeacher().getId()) && option == 1) {
            TeacherSecurityQuestion teacherSecurityQuestion = new TeacherSecurityQuestion();
            teacherSecurityQuestion.setTeacherId(securityQuestion.getTeacher().getId());
            teacherSecurityQuestion.setSecurityQuestionId(securityQuestion.getId());
            teacherSecurityQuestionService.add(teacherSecurityQuestion);
        }

        // teacher, find
        if (option == 2) {
            List<TeacherSecurityQuestion> teacherSecurityQuestions = teacherSecurityQuestionService.findBySecurityQuestionId(securityQuestion.getId());
            for(TeacherSecurityQuestion teacherSecurityQuestion : teacherSecurityQuestions) {
                Long teacherId = teacherSecurityQuestion.getTeacherId();
                Teacher teacher = teacherService.findTeacherById(teacherId);
                securityQuestion.setTeacher(teacher);
            }
        }
    }
}
